package com.example.t410.service.serviceImpl;

import com.example.t410.dao.NootBook;
import com.example.t410.service.NootBookService;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class nootBookServiceImpl implements NootBookService {
    @Autowired
    MongoTemplate mongoTemplate;

//    查询全部
    @Override
    public List<NootBook> select(String userId) {
        Query query=new Query();
        Criteria criteria=Criteria.where("userId").is(userId);
        query.addCriteria(criteria);
        List<NootBook> bookList=mongoTemplate.find(query,NootBook.class);
         return bookList;
    }
//添加记录
    @Override
    public void insertText(NootBook nootBooktext) {
        mongoTemplate.insert(nootBooktext);
    }
//删除记录
    @Override
    public void delect(String userId, Integer memoId) {
        Query query=new Query(Criteria.where("userId").is(userId).and("MemoId").is(memoId));
        DeleteResult result=mongoTemplate.remove(query,NootBook.class);
        long count = result.getDeletedCount();
        log.info("成功删除：{} 条文档",count);
    }
//  根据Id回显数据，用于修改与查看
    @Override
    public NootBook selectId(String userId, Integer memoId) {
        Query query=new Query();
        Criteria criteria=Criteria.where("userId").is(userId).and("MemoId").is(memoId);
        query.addCriteria(criteria);
        List<NootBook> bookList=mongoTemplate.find(query,NootBook.class);
        return bookList.get(0);
    }
//修改更新数据
    @Override
    public void update(NootBook nootBook) {
        Query query=new Query(Criteria.where("userId").is(nootBook.getUserId()).and("MemoId").is(nootBook.getMemoId()));
        nootBook.setTimestamp(System.currentTimeMillis());
        Update update=new Update();
        update.set("Memotext",nootBook.getMemotext());
        update.set("Timestamp",nootBook.getTimestamp());
        UpdateResult result=mongoTemplate.upsert(query,update,NootBook.class);

    }
}
